package com.example.shipload_e.database_dao;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author winaya
 */
public class BizDBAdapter {

	private static final String	DATABASE_NAME	 = "BIZ.db";
	private static final int	DATABASE_VERSION	= 1;

	private static final String	TYPES	         = "CREATE TABLE TYPES( ID VARCHAR2(20),"
	                                                     + " NAME VARCHAR2(20))";

	private static final String	UNITS	         = "CREATE TABLE UNITS( ID VARCHAR2(20),"
	                                                     + " NAME VARCHAR2(20))";

	private static final String	PHOTOS	         = "CREATE TABLE PHOTOS( ID VARCHAR2(50),"
	                                                     + " STATUS VARCHAR2(50),"
	                                                     + " TIME VARCHAR2(50),"
	                                                     + " RESPOND_ID VARCHAR2(50),"
	                                                     + " FILE_NAME VARCHAR2(20))";

	private final Context	    context;
	private DatabaseHelper	    DBHelper;
	private SQLiteDatabase	    db;

	public BizDBAdapter(Context ctx) {
		this.context = ctx;
		setDBHelper(new DatabaseHelper(context));
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				db.execSQL(TYPES);
			} catch (SQLException e) {}
			try {
				db.execSQL(UNITS);
			} catch (SQLException e) {}
			try {
				db.execSQL(PHOTOS);
			} catch (SQLException e) {}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
			onCreate(db);
		}
	}

	private BizDBAdapter open() {
		db = getDBHelper().getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
		getDBHelper().close();
	}

	/**
	 * 获取db connection，进行增删改查操作
	 * @return
	 */
	public SQLiteDatabase openDBConnection() {
		open();
		return db;
	}

	public DatabaseHelper getDBHelper() {
		return DBHelper;
	}

	public void setDBHelper(DatabaseHelper dBHelper) {
		DBHelper = dBHelper;
	}

	public Context getContext() {
		return context;
	}

}
